import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Input,
  Modal,
  InputNumber,
  message,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

interface AddCabinetProps extends FormComponentProps {
  dispatch:Dispatch;
  visible: boolean;
  record:any;
  changVisible:(value:boolean) => void;
}

class AddCabinetElem extends Component<AddCabinetProps> {
  handleSave = () => {
    const { form: { validateFields } } = this.props;
    validateFields((errors: any, values: any) => {
      if (errors) return;

      const { dispatch, record } = this.props;
      if (dispatch) {
        const params:any = { ...values };
        if (record.id) params.id = record.id;
        params.discount = params.discount || 0;
        dispatch({
          type: 'bankPayment/saveCabinet',
          payload: params,
        }).then((res:any) => {
          if (res) {
            message.success('添加成功');
            this.onCancel(true);
          }
        });
      }
    });
  }

  onCancel = (value:boolean) => {
    const { changVisible } = this.props;
    changVisible(value);

    const { form: { resetFields } } = this.props;
    resetFields();
  }

  render() {
    const { visible, record, form: { getFieldDecorator } } = this.props;
    return (
      <>
        <Modal
          title={record.id ? '编辑柜体' : '添加柜体'}
          visible={visible}
          onOk={this.handleSave}
          okText="保存"
          onCancel={() => this.onCancel(false)}
        >
          <Form hideRequiredMark className="tableListForm">
            <Row gutter={12}>
              <Form.Item
                label="柜体编号"
                style={{ width: '80%', margin: '0 auto 24px auto' }}
              >
                {getFieldDecorator('cabCode', {
                  initialValue: record.cabCode,
                  rules: [{ required: true, message: '请输入柜体编号' }],
                })(
                  <Input placeholder="请输入柜体编号" autoComplete="off" />,
                )}
              </Form.Item>
              <Form.Item
                label="　　折扣"
                style={{ width: '80%', margin: '0 auto 12px auto' }}
              >
                {getFieldDecorator('discount', {
                  initialValue: record.discount || '',
                })(
                  <InputNumber min={0} max={10} placeholder="请输入折扣" style={{ width: '100%' }} />,
                )}
              </Form.Item>
            </Row>
          </Form>
        </Modal>
      </>
    );
  }
}

export default Form.create<AddCabinetProps>()(AddCabinetElem);
